#! python3
#! -*- coding:utf-8 -*-

import os, sys, threading, time, random, json5


def ProgressBar(total_time):
    sys.stdout.write(' '*50 + '\r')

    i = 0
    per_time = total_time / 50
    while i <= 50:
        sys.stdout.write('[' + '='*i + ('>' if i < 50 else '') + (50-i-1)*'-' + '] ' + str(int((per_time*i/total_time)*100)) + '%'+ ' '*(3-len(str(i))) +'\r')
        sys.stdout.flush()
        i+=1
        time.sleep(per_time)


def Wait(wait):
    if wait['type'] == 'sleep':
        time.sleep(wait['time'])
    elif wait['type'] == 'progressbar':
        ProgressBar(wait['time'])


def Tap(item):
    point = item['point']
    loop = int(item['loop'])
    wait = item['wait'] if ('wait' in item) else ''

    for i in range(0, loop):
        os.system('adb shell input tap %d %d' % (point[0], point[1]))
        # print('adb shell input tap %d %d' % (point[0], point[1]))

        if wait == '': continue
        Wait(wait)

        if 'then' not in item:
            continue
        Action(item['then'])


def Swipe(item):
    point = item['point']
    loop = int(item['loop'])
    wait = item['wait'] if ('wait' in item) else ''

    for i in range(0, loop):
        os.system('adb shell input swipe %d %d %d %d' % (point[0], point[1], point[2], point[3]))
        # print('adb shell input swipe %d %d %d %d' % (point[0], point[1], point[2], point[3]))

        if wait == '': continue
        Wait(wait)

        if 'then' not in item:
            continue
        Action(item['then'])


def Back(item):
    wait = item['wait'] if ('wait' in item) else ''

    os.system('adb shell input keyevent 4')
    # print('adb shell input keyevent 4')
    
    if wait == '': return
    Wait(wait)


def Action(data):
    for item in data:
        # print('then' not in item)
        action = item['action']
        if action == 'tap':
            Tap(item)
        elif action == 'swipe':
            Swipe(item)
        elif action == 'back':
            Back(item)


def Start(file):
    f = open('./%s' % (file), encoding='utf-8')
    # content = f.read()
    data = json5.load(f)
    Action(data)


# 使用方法： py main.py -f jd.json
if __name__ == '__main__':
    # 读取当前进程ID，可以通过以下命令方式暂停/继续：pssuspend [-r: 继续运行] pid
    pid = os.getpid()
    print('当前PID: %s' % pid)

    dict = {};
    args = sys.argv[1:]
    i = 0
    while(i < len(args)):
        dict[args[i][1:]] = args[i+1]
        i+=2
    if(dict.__contains__('f') == False):
        dict['f'] = 'data.json'

    Start(dict['f'])

    print('\007')
